import { StorageUtil } from '../utils/StorageUtil'
import { Constants } from '../utils/Constants'

/**
 * 购物车服务类
 */
export class CartService {
  private static instance: CartService
  private storageUtil: StorageUtil

  private constructor() {
    this.storageUtil = StorageUtil.getInstance()
  }

  /**
   * 获取单例实例
   */
  static getInstance(): CartService {
    if (!this.instance) {
      this.instance = new CartService()
    }
    return this.instance
  }

  /**
   * 获取购物车数据
   */
  async getCartData(): Promise<any> {
    try {
      return await this.storageUtil.getCartData()
    } catch (error) {
      console.error('获取购物车数据失败:', error)
      return { items: [], total: 0 }
    }
  }

  /**
   * 添加商品到购物车
   */
  async addToCart(item: {
    id: string
    name: string
    price: number
    image: string
    quantity: number
    restaurantId: string
    restaurantName: string
  }): Promise<boolean> {
    try {
      const cartData = await this.getCartData()
      
      // 检查是否来自同一家餐厅
      if (cartData.items.length > 0 && cartData.items[0].restaurantId !== item.restaurantId) {
        // 清空购物车并添加新商品
        cartData.items = [item]
      } else {
        // 查找是否已存在该商品
        const existingItem = cartData.items.find(cartItem => cartItem.id === item.id)
        
        if (existingItem) {
          // 增加数量
          existingItem.quantity += item.quantity
        } else {
          // 添加新商品
          cartData.items.push(item)
        }
      }
      
      // 计算总价
      cartData.total = this.calculateTotal(cartData.items)
      
      // 保存到本地存储
      await this.storageUtil.saveCartData(cartData)
      
      return true
    } catch (error) {
      console.error('添加商品到购物车失败:', error)
      return false
    }
  }

  /**
   * 更新商品数量
   */
  async updateItemQuantity(itemId: string, quantity: number): Promise<boolean> {
    try {
      if (quantity <= 0) {
        return await this.removeFromCart(itemId)
      }
      
      const cartData = await this.getCartData()
      const item = cartData.items.find(cartItem => cartItem.id === itemId)
      
      if (item) {
        item.quantity = quantity
        cartData.total = this.calculateTotal(cartData.items)
        await this.storageUtil.saveCartData(cartData)
        return true
      }
      
      return false
    } catch (error) {
      console.error('更新商品数量失败:', error)
      return false
    }
  }

  /**
   * 从购物车移除商品
   */
  async removeFromCart(itemId: string): Promise<boolean> {
    try {
      const cartData = await this.getCartData()
      cartData.items = cartData.items.filter(item => item.id !== itemId)
      cartData.total = this.calculateTotal(cartData.items)
      
      await this.storageUtil.saveCartData(cartData)
      return true
    } catch (error) {
      console.error('从购物车移除商品失败:', error)
      return false
    }
  }

  /**
   * 清空购物车
   */
  async clearCart(): Promise<boolean> {
    try {
      await this.storageUtil.saveCartData({ items: [], total: 0 })
      return true
    } catch (error) {
      console.error('清空购物车失败:', error)
      return false
    }
  }

  /**
   * 计算购物车总价
   */
  private calculateTotal(items: any[]): number {
    return items.reduce((total, item) => {
      return total + (item.price * item.quantity)
    }, 0)
  }

  /**
   * 获取购物车商品总数
   */
  async getCartItemCount(): Promise<number> {
    try {
      const cartData = await this.getCartData()
      return cartData.items.reduce((count, item) => count + item.quantity, 0)
    } catch (error) {
      console.error('获取购物车商品数量失败:', error)
      return 0
    }
  }

  /**
   * 检查购物车是否为空
   */
  async isCartEmpty(): Promise<boolean> {
    try {
      const cartData = await this.getCartData()
      return cartData.items.length === 0
    } catch (error) {
      console.error('检查购物车状态失败:', error)
      return true
    }
  }

  /**
   * 获取当前餐厅ID
   */
  async getCurrentRestaurantId(): Promise<string | null> {
    try {
      const cartData = await this.getCartData()
      return cartData.items.length > 0 ? cartData.items[0].restaurantId : null
    } catch (error) {
      console.error('获取当前餐厅ID失败:', error)
      return null
    }
  }

  /**
   * 检查是否可以添加商品到购物车
   */
  async canAddToCart(restaurantId: string): Promise<{ canAdd: boolean; message?: string }> {
    try {
      const cartData = await this.getCartData()
      
      if (cartData.items.length === 0) {
        return { canAdd: true }
      }
      
      if (cartData.items[0].restaurantId !== restaurantId) {
        return { 
          canAdd: false, 
          message: '购物车已有其他餐厅的菜品，是否清空购物车？' 
        }
      }
      
      return { canAdd: true }
    } catch (error) {
      console.error('检查购物车状态失败:', error)
      return { canAdd: true }
    }
  }

  /**
   * 强制清空购物车并添加新商品
   */
  async forceAddToCart(item: any): Promise<boolean> {
    try {
      await this.clearCart()
      return await this.addToCart(item)
    } catch (error) {
      console.error('强制添加商品到购物车失败:', error)
      return false
    }
  }

  /**
   * 获取购物车摘要信息
   */
  async getCartSummary(): Promise<{
    itemCount: number
    total: number
    restaurantId: string | null
    restaurantName: string | null
  }> {
    try {
      const cartData = await this.getCartData()
      const itemCount = cartData.items.reduce((count, item) => count + item.quantity, 0)
      
      return {
        itemCount,
        total: cartData.total,
        restaurantId: cartData.items.length > 0 ? cartData.items[0].restaurantId : null,
        restaurantName: cartData.items.length > 0 ? cartData.items[0].restaurantName : null
      }
    } catch (error) {
      console.error('获取购物车摘要信息失败:', error)
      return {
        itemCount: 0,
        total: 0,
        restaurantId: null,
        restaurantName: null
      }
    }
  }
}